<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\Consts;
use app\models\user\DepartmentModel;
use think\facade\Db;
use think\Request;

class DepartmentController extends BaseController
{

    /**
     * 部门列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getList()
    {
        $name = $this->request->param('name');
        $where = [];
        if ($name) {
            $where[] = ['name', '=', $name];
        }
        $list = DepartmentModel::where('status', 0)
            ->where($where)
            ->order('id', 'desc')
            ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
            ->toArray();
        return $this->success($list);
    }

    /**
     * 添加，编辑角色
     * @param Request $request
     * @return \think\response\Json
     */
    public function save()
    {
        try {
            $id = $this->request->param('id', 0);
            $name = $this->request->param('name', '', 'trim');
            if (!$id) {
                $model = new  DepartmentModel();
                $model->name = $name;
                $model->save();
            } else {
                $model = DepartmentModel::find($id);
                $model->name = $name;
                $model->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function del()
    {
        try {
            $id = $this->request->param('id', 0);
            $status = $this->request->param('status', 0);
            $model = DepartmentModel::find($id);
            $model->status = $status;
            $model->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 部门列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getDepartmentArr()
    {
        $list = DepartmentModel::where('status', 0)
            ->order('id', 'desc')
            ->select();
        return $this->success($list);
    }
}
